package com.wx.service.impl;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wx.exception.ServiceException;
import com.wx.mapper.AdvertisementMapper;
import com.wx.mapper.UserMapper;
import com.wx.pojo.Advertisement;
import com.wx.pojo.AdvertisementVO;
import com.wx.pojo.User;
import com.wx.service.AdertisementService;

@Service
public class AdvertisementServiceImpl implements AdertisementService{

	@Autowired
	AdvertisementMapper advertismentMapper;
	@Autowired
	UserMapper userMapper;
	
	//根据广告id，查询一个广告
	@Override
	public AdvertisementVO findAdvertisementById(Integer id) {
		AdvertisementVO advertisementVO = new AdvertisementVO();
		Advertisement advertisement = advertismentMapper.selectById(id);
		advertisementVO.setId(id);
		advertisementVO.setTitle(advertisement.getTitle());
		advertisementVO.setWxqr(advertisement.getWxqr());
		//获取商品ids
		String[] idString = advertismentMapper.findIdsByAdvId(id).split(",");
		Integer[] ids = new Integer[idString.length];
		for (int i=0;i<idString.length;i++) {
			ids[i] = Integer.valueOf(idString[i]);
		}
		for (Integer integer : ids) {
			System.out.print(integer+"   ");
		}
		//通过商品id查询商品
		advertisementVO.setCommoditys(advertismentMapper.findCommoditysByIds(ids));
		return advertisementVO;
	}
	
	
	@Override
	public String addAdver(String token, String title, String commIds) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
			//从数据库查询该token
		User user = userMapper.findUserByToken(token);
			//判断有效性
		if (user==null||!user.getToken().equals(token)) throw new ServiceException("身份信息无效,请登录!");
				
		//验证参数
		/*if(Strings.isEmpty(title)) throw new IllegalArgumentException("标题不能为空");
		String[] commids = commIds.split(",");
		if(commids.length==0) throw new IllegalArgumentException("图片id不能为空！");
		//类型转换
		Integer[] intCommId = new Integer[commids.length];
		for(int i = 0 ;i< commids.length;i++) {
			intCommId[i] = Integer.valueOf(commids[i]);
		}*/
		//if(commIds.length==0) throw new IllegalArgumentException("图片id不能为空！");
		
		//创建广告
		Advertisement advertisement = new Advertisement();
		advertisement.setUserId(user.getId());
		advertisement.setTitle(title);
		advertisement.setWxqr(user.getWechatQrCode());
		advertisement.setCommId(commIds);
		//插入广告
		advertismentMapper.insert(advertisement);
		
		return "http://www.heyclock.com/wxav?id="+advertisement.getId();
	}
	
}